package com.duoec.magichour.core.web.freemarker.portlet;

import com.duoec.magichour.core.web.freemarker.dto.PortletParamDto;
import com.google.common.collect.Maps;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by ycoe on 17/2/27.
 */
public class PortletHelper {
    private static final Map<Class, Map<String, PortletParamDto>> PORTLET_PARAM_DEFAULT_VALUE = Maps.newHashMap();

    private PortletHelper() {
        //私有
    }

    /**
     * 注册Portlet
     *
     * @param <T>
     * @param portlet
     */
    public static <T> Map<String, PortletParamDto> getPortletParamDefalutValueMap(T portlet, Class clazz) {
        Map<String, PortletParamDto> defaultValues = PORTLET_PARAM_DEFAULT_VALUE.get(clazz);
        if(defaultValues != null) {
            return defaultValues;
        }

        defaultValues = Maps.newHashMap();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(PortletParam.class)) {
                continue;
            }
            ReflectionUtils.makeAccessible(field);
            Object value = ReflectionUtils.getField(field, portlet);
            defaultValues.put(field.getName(), new PortletParamDto(value, field));
        }

        Class superClass = clazz.getSuperclass();
        if (superClass != Object.class) {
            Map<String, PortletParamDto> superClassPortletParamMap = getPortletParamDefalutValueMap(portlet, superClass);
            if(!superClassPortletParamMap.isEmpty()) {
                superClassPortletParamMap.forEach(defaultValues::put);
            }
        }

        return defaultValues;
    }

    /**
     * 还原参数
     *
     * @param portlet
     * @param <T>
     */
    public static <T extends BasePortlet> void reset(T portlet) {

    }
}
